#include "rel.h"

/**
 * Parses a received message inside the receiveMessageBuffer array
 * @param none
 * @return none
 *
 * Calls fileStatusCreation with one of the following status types
 *
 * 0 - file exists within directory
 * 1 - file does not exist, requesting transfer
 * 2 - transfer complete
 * 4 - error within message
 */

int parseFileStatusMessage() {

	//ff = filename status message
	if(receiveMessageBuffer[1] == '\x00') {
		//00 response bit = initial request
		if(debug) {
			strcpy(&fileName[0], &receiveMessageBuffer[2]);
			// Declare initial file name length
			fileNameLength = 0;
 			for (fileNameLength; fileNameLength < FILENAME_LEN; fileNameLength++) {
    			if (fileName[fileNameLength] == '\x00') {
      			break;
    			}
  			}// end for
			printf("Response-0: Received new request.\n");
			printf("The name requested is: \"%s\". It is %d long.\n", fileName, fileNameLength);
		}
		if(!sender) {		  
			// Append 'r' in beginning of fileName
			fileName[0] = 'r';
			strcpy(&fileName[1], &receiveMessageBuffer[2]);
		 	fileNameLength = 0;
 			for (fileNameLength; fileNameLength < FILENAME_LEN; fileNameLength++) {
    			if (fileName[fileNameLength] == '\x00') {
      			break;
    			}
  			}// end for
			
			//search current directory for filename with 'r' appended to front
			FILE * checkFile;
			checkFile = fopen(fileName, "rb");
			
			if(checkFile != NULL) {
				if(debug)
					puts("FILE FOUND!");
				fclose(checkFile);
				fileStatusCreation(1);				
				return;
			}
			
			else {
				if(debug)
					puts("FILE NOT FOUND :( ");				
				// Since file does not exist, create
				if(debug)
					printf("Creating file \"%s\".\n", fileName);
				file_open_write();
				// Send FSM(0) to sender
				start = time(NULL);
				
				fileStatusCreation(0);
				
				return;
			}
		}//end receiver
		
		else {
		
			if (file_open_read() < 0) {
  			error("File Open for Reading Error");
  		}
			puts("Receiver does not have the file. Attempting to send...");
			
			// Start Stopwatch
			start = time(NULL);
			
			return createDataMessage();			
		}
	}
	else if(receiveMessageBuffer[1] == '\x01') {
		//01 response bit = file already exists
		if(debug)
			printf("Response-1: Already have file. Check local directory.\n");
		if(!sender) {
			puts("Received acknowledgement from sender. Exiting...");
			exit(0);	
		}
		else {
			puts("Receiver already has that file. I will close soon.");
			
			// Lock sendMessageBuffer
      pthread_mutex_lock ( &mutexLock ); 
			
			sendMessageSize = fileStatusCreation(1);
			
			// UNLock sendMessageBuffer
      pthread_mutex_unlock ( &mutexLock ); 
  		
  			sendUDP(ipAddress, receiverPort, socketfd, sendMessageBuffer, sendMessageSize);  			
  			exit(0);
  			}
	}//end else if
	else if(receiveMessageBuffer[1] == '\x02') {
		if(sender){
			printf("Time elapsed for transfer: %ld sec\n", time(NULL) - start);
		}
		//02 response bit = successful transfer
		if(debug)
			printf("Response-2: Completed transfer. Mission: Success.\n");
		if(!sender) {
			puts("Received acknowledgement for successful transfer. Exiting...");
			exit(0);
		}
		else {
			fileStatusCreation(2);
			sendUDP(ipAddress, receiverPort, socketfd, sendMessageBuffer, sendMessageSize); 
			exit(0);
		}
		
	}//end else if
	else {
		if(debug)
			printf("ERROR: received unknown response. Aborting.\n");
		exit(0);
	}
}//end parseMessage

/**
 * Creates the File Status message within the sendMessageBuffer.
 *
 * @param fileStatus an integer that represents the status for the file status 
 * message
 *
 * @return An integer that represents the message size to return.
 */
 
int fileStatusCreation(int fileStatus) {
 
	int i;
  
	sendMessageBuffer[0] = '\xFF';
	
	switch (fileStatus) {
		case 0:
			if(sender) {
				if(debug)
					printf("Wanting to send \"%s\".\n", fileName);
			}
			else {
				if(debug)
					printf("Requesting file: \"%s\".\n", fileName);
			}
			sendMessageBuffer[1] = '\x00';
			break;
		case 1: 
			if(!sender) {
				printf("The file \"%s\" already exists.\n", fileName);
			}	
			sendMessageBuffer[1] = '\x01';
			break;
		case 2:
			if(!sender){
				printf("\nTime elapsed for transfer: %ld sec\n", time(NULL) - start);
			}
			puts("Transfer was successful.");
			successfulTransfer = true;
			sendMessageBuffer[1] = '\x02';
			break;
		default:
			puts("Oops, something went wrong...");
			sendMessageBuffer[1] = '\x04';
			break;
	}//end switch
	
	if(sender) {
		for(i = 0; i < fileNameLength; i++) {
			sendMessageBuffer[i+2] = fileName[i];
		}
		sendMessageBuffer[i+2] = '\x00';
  	}
  else{
  	for(i = 0; i < fileNameLength; i++) {
			sendMessageBuffer[i+2] = fileName[i+1];
		}
		sendMessageBuffer[i+2] = '\x00';
  	}
  // Set message size = FF + response byte + filename + 00
  sendMessageSize = fileNameLength + 3;  
  if (debug) {
    printMessage(sendMessageBuffer, sendMessageSize);
  }

  return sendMessageSize;
  	
 }//end responseMessage
 